package com.cheng.api_getway_zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.cheng.api_getway_zuul.feign.JWTService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wangke
 */
@Component
public class LoginFilter extends ZuulFilter {
    @Autowired
    private JWTService jwtService;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return false;
        ////共享RequestContext，上下文对象
        //RequestContext requestContext = RequestContext.getCurrentContext();
        //HttpServletRequest request = requestContext.getRequest();
        ////登录接口不需要校验
        //if (request.getRequestURI().contains("api-jwt")) {
        //    return false;
        //}
        //if ("/api-jwt/user/login".equalsIgnoreCase(request.getRequestURI())) {
        //    return false;
        //}
        //return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletResponse rep = ctx.getResponse();
        HttpServletRequest request = ctx.getRequest();
        //设置允许跨域的配置
        // 这里填写你允许进行跨域的主机ip（正式上线时可以动态配置具体允许的域名和IP）
        rep.setHeader("Access-Control-Allow-Origin", rep.getHeader("Origin"));
        rep.setHeader("Access-Control-Allow-Credentials", "true");
        // 允许的访问方法
        rep.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
        // Access-Control-Max-Age 用于 CORS 相关配置的缓存
        rep.setHeader("Access-Control-Max-Age", "3600");
        rep.setHeader("Access-Control-Allow-Headers", "token,Origin, X-Requested-With, Content-Type, Accept");
        return null;
    }
}
